package org.tinyGame.heroStory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

public class ServerMain {
    public static void main(String[] args) {
        //2个线程池
        //处理客户端连接(只负责链接)
        EventLoopGroup bossLoop = new NioEventLoopGroup();
        //读写客户端的字节流消息(负责业务)
        EventLoopGroup workerLoop = new NioEventLoopGroup();

        ServerBootstrap b = new ServerBootstrap();
        b.group(bossLoop,workerLoop);
        //处理服务器信号？？ 不确定
        b.channel(NioServerSocketChannel.class);
        //处理客户端
        b.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(
                        //游戏基于web 需要http编解码器
                        new HttpServerCodec(),
                        //限制消息长度
                        new HttpObjectAggregator(65535),
                        new WebSocketServerProtocolHandler("/websocket")
                );
            }
        });
        try {
            ChannelFuture f = b.bind(12345).sync();
            if(f.isSuccess()){
                System.out.println("服务器启动成功");
            }
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
